import {defineStore} from "pinia";
import router from "@/router";

interface LayoutSet {
    headerHeight: string,
    sidebarCollapse: boolean,
    theme: string,
    mode: string,
    navTabs: Array<any>     // 打开的页面
    mainHeight: number,
    title: "超级管理系统"
}

// @ts-ignore
const set = JSON.parse(localStorage.getItem("layoutSet")) || ''

export const useLayoutSetStore = defineStore("layoutSet", {
    state: ():LayoutSet => ({
        headerHeight: '60px',
        sidebarCollapse: false,
        theme: set.theme ? set.theme : "#409eff",
        mode: set.mode ? set.mode : "light",
        navTabs:[],
        mainHeight: 0,
        title:"超级管理系统"
    }),
    actions: {
        setTheme(color:string){
            this.theme = color
        },
        setMode(mode:string){
            this.mode = mode
        },
        addNavTab(route:any){
            let path = route.path
            if (this.navTabs.some( v => v.path === path) || path == '/' || path == '/index') return;
            this.navTabs.push(
                Object.assign({}, route, {
                    title: route.meta.title || 'no-name'
                })
            )
        },

        removeNavTab(route:any){
            let index = this.navTabs.findIndex( v => v.path === route.path)
            if (index !== -1){
                // 到下一个路由
                if (index+1 < this.navTabs.length){
                    router.push(this.navTabs[index+1])
                }else{
                    router.push("/index")
                }
                this.navTabs.splice(index,1)
            }
        },
        removeLeftTabs(route:any){

            let index:number = this.navTabs.findIndex( v => v.path === route.path)

            this.navTabs = this.navTabs.filter((v,i) => {
                return i >= index
            })
            // 跳转路由
            router.push(route)

        },

        removeRightTabs(route:any){
            let index:number = this.navTabs.findIndex( v => v.path === route.path)

            this.navTabs = this.navTabs.filter((v,i) => {
                return i <= index
            })
            // 路由
            router.push(route)
        },

        removeOtherTabs(route:any){
            let index:number = this.navTabs.findIndex( v => v.path === route.path)
            for (let i in this.navTabs){
                let ii = parseInt(i)
                if (ii != index){
                    this.navTabs.splice(ii,1)
                }
            }
            router.push(route)
        },
        removeAllTabs(){
            this.navTabs = []
            router.push("/index")
        }
    }
})
